# numpy 矩阵运算
import numpy as np

a1 = np.array([[4, 5, 6], [1, 2, 3]])
a2 = np.array([[6, 5, 4], [3, 2, 1]])

# 矩阵点乘，即对应元素相乘
print(a1 * a2)
# 输出
# [[24 25 24]
#  [ 3  4  3]]

# 矩阵点乘，每个元素乘以一个数
print(a1 * 3)
# 输出
# [[12 15 18]
#  [ 3  6  9]]

# 矩阵相乘，（2*3）*（2*3）是报错的，维度不对应
# 需要先对a2转置
a3 = a2.T  # 转置
print(np.dot(a1, a3))  # 矩阵相乘要用 np.dot 函数
# 输出
# [[73 28]
#  [28 10]]

# 矩阵转置
print(a1.T)
# 输出
# [[4 1]
#  [5 2]
#  [6 3]]

# 矩阵求逆
a = np.array([[1, 2, 3], [4, 5, 6], [5, 4, 3]])
print(np.linalg.inv(a))
# 输出
# [[ 2.25179981e+15 -1.50119988e+15  7.50599938e+14]
#  [-4.50359963e+15  3.00239975e+15 -1.50119988e+15]
#  [ 2.25179981e+15 -1.50119988e+15  7.50599938e+14]]

# 特征值与特征向量
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
eigenValues, eigVector = np.linalg.eig(a)
# 得到三个特征值及其对应的特征向量
# 特征值是
# array([ 1.61168440e+01, -1.11684397e+00, -1.30367773e-15])
# 对应的特征向量是
# array([[-0.23197069, -0.78583024,  0.40824829],
#        [-0.52532209, -0.08675134, -0.81649658],
#        [-0.8186735 ,  0.61232756,  0.40824829]])


# svd 奇异值分解
U, sigma, V = np.linalg.svd(a, full_matrices=False)
# U 值是
# array([[-0.21483724,  0.88723069,  0.40824829],
#        [-0.52058739,  0.24964395, -0.81649658],
#        [-0.82633754, -0.38794278,  0.40824829]])
# sigma 值是
# array([1.68481034e+01, 1.06836951e+00, 4.41842475e-16])
# V 值是
# array([[-0.47967118, -0.57236779, -0.66506441],
#        [-0.77669099, -0.07568647,  0.62531805],
#        [-0.40824829,  0.81649658, -0.40824829]])


# 矩阵的行列式
value = np.linalg.det(a)
# 输出 0

# QR 分解
Q, R = np.linalg.qr(a)
# Q 值是
# array([[-8.12403840e+00, -9.60113630e+00, -1.10782342e+01],
#        [ 0.00000000e+00,  9.04534034e-01,  1.80906807e+00],
#        [ 0.00000000e+00,  0.00000000e+00, -8.88178420e-16]])
# R 值是
# array([[-8.12403840e+00, -9.60113630e+00, -1.10782342e+01],
#        [ 0.00000000e+00,  9.04534034e-01,  1.80906807e+00],
#        [ 0.00000000e+00,  0.00000000e+00, -8.88178420e-16]])
